﻿using CPAIS.Adapter;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;

namespace CPAIS.Web
{
    public partial class HLDAPatternGraph : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            PatternChart.ChartAreas["ChartArea"].Area3DStyle.Inclination = int.Parse(Inclination.SelectedItem.Text);
            PatternChart.ChartAreas["ChartArea"].Area3DStyle.Rotation = int.Parse(RotateY.SelectedItem.Text);
            PatternChart.ChartAreas["ChartArea"].Area3DStyle.Perspective = int.Parse(Perspective.SelectedItem.Text);

            double filterActivities = 0.01;
            double filterTimestamps = 0.01;
            {
                string filterAText = FilterActivities.SelectedItem.Text;
                string filterTText = FilterTimestamps.SelectedItem.Text;
                double filterA = 0;
                double filterT = 0;
                if (double.TryParse(filterAText, out filterA) && filterA > 0)
                    filterActivities = filterA;
                if (double.TryParse(filterTText, out filterT) && filterT > 0)
                    filterTimestamps = filterT;
            }

            string logName = Request.Params[Constants.LogName];
            string index = Request.Params[Constants.Index];
            if (logName != null && index != null)
            {
                int nIndex = int.Parse(index);
            

                MLManager mlManager = Session[Constants.MLManager] as MLManager;
                HLDAGibbsAdapter adapter = mlManager.GetHLDAAdapter(logName);
                PatternChart.Series.Clear();
                if (adapter != null)
                {
                    var topics = adapter.TopicWordAssoc;
                    var topic = topics[nIndex];

                    string format = "<span style=\"color: #000000; font-size: 15px;\">{0}:</span>&nbsp;&nbsp;<span style=\"color: #cc5588; font-size: 15px;\">{1}</span>&nbsp;&nbsp;&nbsp;&nbsp;";
                    Log.InnerHtml = string.Format(format, "Log Name:", logName);
                    Index.InnerHtml = string.Format(format, "Topic Name:", topic.name);

                    PatternChart.Titles[0].Text = string.Format("Pattern {0} Discovered By HLDA ({1})", topic.name, topic.Prob.ToString("0.0000"));
                    List<string> actionList = new List<string>();
   
                    char[] opertors = new char[1];
                    opertors[0] = ':';

                    foreach (var action in topic.Actions)
                    {
                        string[] substrings = action.ActionType.Split(opertors);
                        if(actionList.Contains(substrings[0].Trim()) == false)
                            actionList.Add(substrings[0].Trim());
                    }

                    foreach(string actionName in actionList)
                    {
                         List<int> days = new List<int>();
                         List<int> freqs = new List<int>();
                         List<double> probs = new List<double>();
                         foreach(var action in topic.Actions)                    
                         {
                           
                               string[] substrings = action.ActionType.Split(opertors);
                               if (substrings[0].Trim().Equals(actionName) == false)
                                   continue;
                               else
                               {
                                   int nDay = Convert.ToInt32(substrings[1].Trim());

                                   if (action.ActionProb >= filterTimestamps)
                                   {
                                       days.Add(nDay + 1);
                                       freqs.Add(action.ActionCount);
                                       probs.Add(action.ActionProb);
                                   }
                               }
                            }
                    
                            Series series = new Series(actionName);

                            string mode = SwitchMode.SelectedItem.Text;
                            var axisY = PatternChart.ChartAreas["ChartArea"].AxisY;
                            axisY.Title = mode;
                            if (mode == "Probability")
                            {
                                axisY.Interval = 0.1;
                                series.Points.DataBindXY(days, probs);
                            }
                            else
                            {
                                int maxCount = int.MinValue;
                                foreach (var i in freqs)
                                {
                                    if (maxCount < i)
                                        maxCount = i;
                                }
                                axisY.Interval = maxCount / 10;
                                series.Points.DataBindXY(days, freqs);
                            }

                            series.Tag = actionName;
                            PatternChart.Series.Add(series);
                        }
                }

            }
        }

        protected void EditFilterActivities_TextChanged(object sender, EventArgs e)
        {
            double filterA = 0;
            if (double.TryParse(EditFilterActivities.Text, out filterA) && filterA >= 0)
            {
                bool existed = false;
                foreach (ListItem item in FilterActivities.Items)
                {
                    if (item.Text == EditFilterActivities.Text)
                    {
                        existed = true;
                        break;
                    }
                }
                if (!existed)
                    FilterActivities.Items.Add(EditFilterActivities.Text);
                FilterActivities.SelectedValue = EditFilterActivities.Text;
                Page_Load(sender, e);
            }
            else
                EditFilterActivities.Text = "0.01";
        }

        protected void FilterActivities_SelectedIndexChanged(object sender, EventArgs e)
        {
            EditFilterActivities.Text = FilterActivities.SelectedItem.Text;
        }

        protected void EditFilterTimestamps_TextChanged(object sender, EventArgs e)
        {
            double filterA = 0;
            if (double.TryParse(EditFilterTimestamps.Text, out filterA) && filterA >= 0)
            {
                bool existed = false;
                foreach (ListItem item in FilterTimestamps.Items)
                {
                    if (item.Text == EditFilterTimestamps.Text)
                    {
                        existed = true;
                        break;
                    }
                }
                if (!existed)
                    FilterTimestamps.Items.Add(EditFilterTimestamps.Text);
                FilterTimestamps.SelectedValue = EditFilterTimestamps.Text;
                Page_Load(sender, e);
            }
            else
                EditFilterTimestamps.Text = "0.01";
        }

        protected void FilterTimestamps_SelectedIndexChanged(object sender, EventArgs e)
        {
            EditFilterTimestamps.Text = FilterTimestamps.SelectedItem.Text;
        }

        protected void SwitchMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            Page_Load(sender, e);
        }
    }
}